package org.jeecg.modules.demo.puInvoice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.advancesReceived.entity.YxAdvancesReceived;
import org.jeecg.modules.demo.puInvoice.entity.PuInvoice;
import org.jeecg.modules.demo.puInvoice.service.IPuInvoiceService;
import org.jeecg.modules.demo.pubuyorder.entity.PuBuyOrder;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlement;
import org.jeecg.modules.demo.pusettlement.service.IPuSettlementService;
import org.jeecg.modules.demo.sopayorder.service.ISoPayorderService;
import org.jeecg.modules.demo.utils.BigDecimalUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

 /**
 * @Description: pu_invoice
 * @Author: jeecg-boot
 * @Date:   2021-12-16
 * @Version: V1.0
 */
@Api(tags="pu_invoice")
@RestController
@RequestMapping("/puInvoice/puInvoice")
@Slf4j
public class PuInvoiceController extends JeecgController<PuInvoice, IPuInvoiceService> {
	@Autowired
	private IPuInvoiceService puInvoiceService;
	@Autowired
	private ISoPayorderService soPayorderService;
	@Autowired
	private IPuSettlementService puSettlementService;
	@Autowired
	private IPuBuyOrderService puBuyOrderService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;


	/**
	 * 分页列表查询
	 *
	 * @param puInvoice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购发票-分页列表查询")
	@ApiOperation(value="采购发票-分页列表查询", notes="采购发票-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/puInvoice/PuInvoiceList")
	public Result<?> queryPageList(PuInvoice puInvoice,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<PuInvoice> queryWrapper = QueryGenerator.initQueryWrapper(puInvoice, req.getParameterMap());
			queryWrapper.eq("SHANCHU",0);
			Page<PuInvoice> page = new Page	<PuInvoice>(pageNo, pageSize);
			IPage<PuInvoice> pageList = puInvoiceService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	/**
	 *   添加
	 *
	 * @param puInvoice
	 * @return
	 */
	@AutoLog(value = "采购发票-添加")
	@ApiOperation(value="采购发票-添加", notes="采购发票-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PuInvoice puInvoice,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			String str = puInvoiceService.getMaxCode();
			Map<String,String> map = new HashMap<>();
			map.put("maxCode",str==null?null:str);
			String name =precode+ "FP_";
			String resultCode = generateOddUtil.createCode(map,name);
			puInvoice.setId(null);
			puInvoice.setPuiNo(resultCode);
			puInvoice.setYjjine(puInvoice.getHsje());
			puInvoice.setShenhe(0);
			puInvoice.setShanchu(0);
			puInvoice.setCreateTime(new Date());
			if(puInvoiceService.addSettlementInvoice(puInvoice,precode)){
				return Result.OK("成功！");
			}
			return Result.error(500,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	 /**
	  *   预开发票
	  *
	  * @param puInvoice
	  * @return
	  */
	 @AutoLog(value = "采购发票-预开发票")
	 @ApiOperation(value="采购发票-预开发票", notes="采购发票-预开发票")
	 @PostMapping(value = "/addInvoice")
	 public Result<?> addInvoice(@RequestBody PuInvoice puInvoice,HttpServletRequest req) {
		 try{
			 //TODO 限制条件
			 if(puInvoice.getReceiptNumber()!=null){
			 	if(puInvoice.getYfuseje()==null){
			 		return Result.error(300,"请填写预付款本次使用金额！");
				}
			 }
			 List<PuInvoice> invoices =puInvoiceService.getByPoOrder(puInvoice.getPoOrder());
			 if(!invoices.isEmpty()){
				 return Result.error(300,"该订单已有采购发票，无法预开发票！");
			 }
			 String tenantId = req.getHeader("tenant-id");
			 String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			 String str = puInvoiceService.getMaxCode();
			 Map<String,String> map = new HashMap<>();
			 map.put("maxCode",str==null?null:str);
			 Map<String,BigDecimal>  map1 = puInvoiceService.getNumByOrderAndLX(puInvoice.getPoOrder());
			 BigDecimal d1 =map1.get("SHUL");
			 BigDecimal d2 = map1.get("JINE");
			 Double sl = BigDecimalUtil.add(puInvoice.getQoQuantity().doubleValue(),d1.doubleValue());
			 Double zj = BigDecimalUtil.add(puInvoice.getHsje().doubleValue(),d2.doubleValue());
			 PuBuyOrder puBuyOrder = puBuyOrderService.getByNumber(puInvoice.getPoOrder());
			 if(sl > puBuyOrder.getPoTotail().doubleValue() || zj > puBuyOrder.getHsje()){
				return Result.error(300,"累计预开票数量或金额不能大于订单数量或金额！");
			 }
			 String name =precode+ "FP_";
			 String resultCode = generateOddUtil.createCode(map,name);
			 puInvoice.setId(null);
			 puInvoice.setPuiNo(resultCode);
			 puInvoice.setShenhe(0);
			 puInvoice.setShanchu(0);
			 puInvoice.setCreateTime(new Date());
			 puInvoice.setFpsl(puInvoice.getQoQuantity());
			 puInvoice.setHsje(puInvoice.getSupamount());
			 puInvoice.setYjjine(puInvoice.getHsje());
			 puInvoice.setTradecode(puBuyOrder.getTradecode());
			 if(puInvoiceService.addInvoice(puInvoice,precode)){
				 return Result.OK("成功！");
			 }
			 return Result.error(500,"失败！");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }
	 /**
	  *  审核
	  *
	  * @param puInvoice
	  * @return
	  */
	 @AutoLog(value = "采购发票-审核")
	 @ApiOperation(value="采购发票-审核", notes="采购发票-审核")
	 @PostMapping(value = "/checkInvoice")
	 public Result<?> checkInvoice(@RequestBody PuInvoice puInvoice) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(puInvoice.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(puInvoice.getShenhe()==1){
				 return Result.error(300,"单据已审核！");
			 }
			 if(puInvoiceService.checkInvoice(puInvoice)){
				 return Result.OK("审核成功!");
			 }
			 return Result.error(500,"审核失败！");
		 }catch (Exception e){
		 	e.printStackTrace();
		 	return Result.error(500,"系统错误！");
		 }
	 }
	 /**
	  *  弃审
	  *
	  * @param puInvoice
	  * @return
	  */
	 @AutoLog(value = "采购发票-弃审")
	 @ApiOperation(value="采购发票-弃审", notes="采购发票-弃审")
	 @PostMapping(value = "/unCheckInvoice")
	 public Result<?> unCheckInvoice(@RequestBody PuInvoice puInvoice) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(puInvoice.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(puInvoice.getShenhe()==0){
				 return Result.error(300,"请先审核单据！");
			 }

			 if(Integer.parseInt(puInvoice.getFplx())!=4){
				 List<String> ids = soPayorderService.selectByPuiNo(puInvoice.getPuiNo());
				 if(!ids.isEmpty()){
					 return Result.error(300,"已生成付款单，无法弃审！");
				 }
			 }
			 if(puInvoiceService.unCheckInvoice(puInvoice)){
				 return Result.OK("弃审成功!");
			 }


			 return Result.error(500,"弃审失败!");
		 }catch (Exception e){
		 	e.printStackTrace();
		 	return Result.error(500,"系统错误!");
		 }
	 }
	/**
	 *  编辑
	 *
	 * @param puInvoice
	 * @return
	 */
	@AutoLog(value = "采购发票-编辑")
	@ApiOperation(value="采购发票-编辑", notes="采购发票-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PuInvoice puInvoice,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			if(puInvoice.getShenhe()==1){
				return Result.error(300,"单据已审核，无法编辑！");
			}
			Double yj =puInvoice.getYjjine().doubleValue();
			Double sf=0.000;
			if(puInvoice.getSupamount()!=null){
				sf= puInvoice.getSupamount().doubleValue();
			}else{
				puInvoice.setSupamount(new BigDecimal(sf));
			}
			puInvoice.setYjjine(new BigDecimal(BigDecimalUtil.sub(yj,sf)));

			if(puInvoiceService.editInvoice(puInvoice,precode)){
				return  Result.OK("编辑成功!");
			}
			return Result.error(500,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	@PostMapping(value = "/queryYf")
	public  String queryYf(@RequestBody PuInvoice puInvoice){
		Gson gson = new Gson();
		Map map = new HashMap();
		try{
			List<YxAdvancesReceived> advancesReceiveds = puInvoiceService.getYfByPoOrder(puInvoice.getPoOrder());
			if(puInvoice.getReceiptNumber()!=null){
				for (YxAdvancesReceived advancesReceived : advancesReceiveds) {
					if(advancesReceived.getReceiptNumber().equals(puInvoice.getReceiptNumber())){
						advancesReceived.setSupAmount(new BigDecimal(BigDecimalUtil.add(puInvoice.getYfuseje().doubleValue(),advancesReceived.getSupAmount().doubleValue())));
					}
				}
			}
			map.put("advancesReceiveds",advancesReceiveds);
			map.put("code",200);
			map.put("message","成功！");
			String json = gson.toJson(map);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",500);
			map.put("message","系统错误！");
			String json = gson.toJson(map);
			return json;
		}
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购发票-通过id删除")
	@ApiOperation(value="采购发票-通过id删除", notes="采购发票-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			PuInvoice puInvoice = puInvoiceService.getById(id);
			if(puInvoice.getShenhe()==1){
				return Result.error(300,"单据已审核，无法删除！");
			}
			if(Integer.parseInt(puInvoice.getFplx())==4){
				List<PuSettlement> puSettlements = puSettlementService.getListByPoOrder(puInvoice.getPoOrder());
				if(!puSettlements.isEmpty()){
					return  Result.error(300,"已生成结算单，无法删除预开发票！");
				}
			}
			if(puInvoiceService.deleteById(puInvoice)){
				return  Result.OK("删除成功!");
			}

			return  Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}
	@PostMapping(value = "/getYFData")
	public String getYFData(@RequestParam(name="str",required=true)String str){
		Gson gson = new Gson();
		Map map = new HashMap();
		try{
			Map<String,Double> stringDoubleMap = puInvoiceService.getYFData(str);
			map.put("yfzje",stringDoubleMap.get("YFZJE"));
			map.put("syje",stringDoubleMap.get("SYJE"));
			map.put("useje",stringDoubleMap.get("USEJE"));
			String json = gson.toJson(map);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",500);
			map.put("message","系统错误！");
			String json = gson.toJson(map);
			return json;
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购发票-批量删除")
	@ApiOperation(value="采购发票-批量删除", notes="采购发票-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.puInvoiceService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购发票-通过id查询")
	@ApiOperation(value="采购发票-通过id查询", notes="采购发票-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PuInvoice puInvoice = puInvoiceService.getById(id);
		if(puInvoice==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(puInvoice);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param puInvoice
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PuInvoice puInvoice) {
        return super.exportXls(request, puInvoice, PuInvoice.class, "pu_invoice");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PuInvoice.class);
    }

}
